package demo7;

import java.util.Comparator;

class Student implements Comparable<Student>{
    public String name;
    public int age;
    public double score;

    public Student(String name, int age, double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        /*if (this.age - o.age > 0){
            return 1;
        }else if (this.age - o.age == 0){
            return 0;
        }else{
            return -1;
        }*/
        return this.age-o.age;//从小到大排序
//        return o.age-this.age;//从大到小排序
    }
}
//利用接口Comparator,相比较接口Comparable更加的灵活，解耦性，因为之前的Comparable是通过compareTo来决定按照哪个指标进行排序，
// 如果需要修改排序的指标需要进入Student这个类里面进行修改，不方便，同时保留不了使用原本指标的功能
class ageComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}
class scoreComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return (int)(o1.score - o2.score);
    }
}

public class Test {
    public static void main(String[] args) {
        Student student1 = new Student("zhangsan",14,30.9);
        Student student2 = new Student("lisi",15,89.1);
        ageComparator agecomparator = new ageComparator();
        int ret = agecomparator.compare(student1,student2);
        System.out.println(ret);
        scoreComparator scorecomparator = new scoreComparator();
        int ret2 = scorecomparator.compare(student1,student2);
        System.out.println(ret2);
    }
}
